import os
import sys


class PathUtils:
    """路径工具类，处理跨平台路径问题"""
    
    @staticmethod
    def get_absolute_path(path: str) -> str:
        """获取绝对路径"""
        if os.path.isabs(path):
            return path
        else:
            return os.path.abspath(path)
    
    @staticmethod
    def normalize_path(path: str) -> str:
        """规范化路径，确保使用正确的分隔符"""
        return os.path.normpath(path)
    
    @staticmethod
    def ensure_directory(path: str) -> str:
        """确保目录存在，如果不存在则创建"""
        path = PathUtils.get_absolute_path(path)
        os.makedirs(path, exist_ok=True)
        return path
    
    @staticmethod
    def get_executable_path(executable_name: str) -> str:
        """获取可执行文件的完整路径 - 仅使用tools目录"""
        # 首先检查当前目录
        current_dir = os.path.dirname(os.path.abspath(__file__))
        root_dir = os.path.dirname(current_dir)
        
        # 仅使用tools目录作为搜索路径
        search_paths = [
            os.path.join(root_dir, 'tools', executable_name),  # 仅tools目录
            os.path.join(os.getcwd(), 'tools', executable_name),  # 仅tools目录
        ]
        
        for path in search_paths:
            if os.path.exists(path):
                return PathUtils.get_absolute_path(path)
        
        # 如果在PATH环境变量中
        for path in os.environ.get('PATH', '').split(os.pathsep):
            full_path = os.path.join(path, executable_name)
            if os.path.exists(full_path):
                return full_path
        
        return executable_name
    
    @staticmethod
    def quote_path(path: str) -> str:
        """为Windows命令行引用路径"""
        # 如果路径包含空格或特殊字符，添加引号
        if ' ' in path or '&' in path or '(' in path or ')' in path:
            return f'"{path}"'
        return path

    @staticmethod
    def get_m3u8_downloader_path():
        """获取M3U8下载器路径"""
        return os.path.join(PathUtils.get_project_root(), 'tools', 'N_m3u8DL-CLI_v3.0.2.exe')

    @staticmethod
    def get_ffmpeg_path():
        """获取FFmpeg路径"""
        return os.path.join(PathUtils.get_project_root(), 'tools', 'ffmpeg.exe')